package cs4280.ass2.action;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import cs4280.ass2.entity.Member;
import cs4280.ass2.entity.User;
import cs4280.ass2.exception.ValidateException;
import cs4280.ass2.persistence.MemberDao;
import cs4280.ass2.util.MemberUtils;

public class RegisterAction extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String login = StringUtils.trim(req.getParameter("login"));
		String password = StringUtils.trim(req.getParameter("password"));
		String firstName = StringUtils.trim(req.getParameter("firstName"));
		String lastName = StringUtils.trim(req.getParameter("lastName"));

		Member m = new Member();
		m.setLogin(login);
		m.setPassword(password);
		m.setFirstName(firstName);
		m.setLastName(lastName);
		m.setAppUserStatus(User.APP_USER_ACTIVE);
		m.setCreateDate(new Date());
		m.setCreateUser(0);
		m.setModifyDate(new Date());
		m.setModifyUser(0);

		try {
			MemberUtils.validate(m);
			MemberDao.getInstance().registerMember(m);

			req.setAttribute("message.info", "message.info.register.success");
			getServletContext().getRequestDispatcher("/index.jsp").forward(req, resp);
		} catch (ValidateException e) {
			req.setAttribute("message.error", e.getMessage());
			getServletContext().getRequestDispatcher("/register.jsp").forward(req, resp);
		}
	}
}
